﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using Formsy.Data.Services;
using System.Configuration;
using Anthony.Library;
using System.Data.SqlTypes;
using Anthony.Library.Entensions;
using System.Web.UI.HtmlControls;
using Formsy.Common;
using System.Xml.Linq;
using System.Text;
using Formsy.Config;
using Formsy.Core.Resources;


namespace Formsy.Core
{
    public partial class CSVDownload : WebControl
    {
        #region Public Properties

        // comma separated list of headings to NOT output.
        public string IgnoreList { get; set; }

        // the form name as it was in the form definition
        public string FormName { get; set; }

        // allows developer to use default style
        public bool UseDefaultStyle { get; set; }

        public bool RequiredValidatorsEnabled { get; set; }

        // to allow explicit id 
        public override string ClientID
        {
            get
            {
                return "FormsyCsv";
            }
        }

        #endregion



        #region Protected Members

        protected ControlBuilder m_ControlBuilder;

        protected List<FormField> m_FormFields;

        #endregion



        #region OnLoad

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            m_ControlBuilder = new ControlBuilder();
            m_FormFields = new List<FormField>();

            // set a default id if one is not given
            if (ID == null)
                ID = "Formsy" + FormName + "Csv";
            
            EnsureChildControls();
            DataBind();
        }

        #endregion



        #region OnPreRender

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            m_ControlBuilder.AddFormsyLogo();

            // register default css
            if (UseDefaultStyle)
            {
                m_ControlBuilder.AddResource(EmbededResource.AdminCSVDefaultStyle, ResourceType.Style);
            }
        }

        #endregion



        #region CreateChildControls

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            HtmlGenericControl div = m_ControlBuilder.CreateHtmlControl(ControlType.Div, ID, string.Empty);

            // create validation summary
            ValidationSummary vs = m_ControlBuilder.CreateValidationSummary(FormName, true.ToString());
            div.Controls.Add(vs);

            // create fieldset
            HtmlGenericControl fieldSet = m_ControlBuilder.CreateHtmlControl(ControlType.FieldSet, ClientID, string.Empty);

            // add form title
            m_ControlBuilder.AddEnclosedLiteral(fieldSet, ControlType.H3, "CSV Extract", "CSV Extract", string.Empty);



            HtmlGenericControl divFrom = m_ControlBuilder.CreateHtmlControl(ControlType.Div, "From Date", ClientStrings.Default.FieldClass);
            HtmlGenericControl divTo = m_ControlBuilder.CreateHtmlControl(ControlType.Div, "To Date", ClientStrings.Default.FieldClass);

            m_ControlBuilder.AddTypeAsClass(divFrom, ControlType.DatePicker);
            m_ControlBuilder.AddTypeAsClass(divTo, ControlType.DatePicker);

            // create from date date picker
            Control fromDate = m_ControlBuilder.CreateDatePicker("From", divFrom, this, m_FormFields, "Formsy" + FormName + "Csv", fieldSet, ControlType.RequiredFieldValidator, "*", "Please select a \"from\" date", "Dynamic", RequiredValidatorsEnabled);

            // create to date date picker
            Control toDate = m_ControlBuilder.CreateDatePicker("To", divTo, this, m_FormFields, "Formsy" + FormName + "Csv", fieldSet, ControlType.RequiredFieldValidator, "*", "Please select a \"from\" date", "Dynamic", RequiredValidatorsEnabled);

            // add container to fieldset
            fieldSet.Controls.Add(divFrom);
            fieldSet.Controls.Add(divTo);


            // add submit button
            Button button = m_ControlBuilder.CreateButton("Submit", "Formsy" + FormName + "Csv", "Get Csv");
            button.Click += new EventHandler(Button_Click);
            fieldSet.Controls.Add(button);

            // add button to fieldset
            fieldSet.Controls.Add(button);

            // add fieldset to containing div
            div.Controls.Add(fieldSet);

            // add div to page
            this.Controls.Add(div);
        }

        #endregion



        #region CsvButton_Click

        protected void Button_Click(object sender, EventArgs e)
        {
            // check if form exists.
            var form = HttpDataService.Instance.FormsyService.GetForm(FormName);
            if (form == null)
            {
                // throw a meaningful error :)
                throw new Exception("Form " + FormName + " does not exist.");
            }

            string path = Formsy.Config.Settings.Instance.FormsyAppSettings.FormsyFilePath + FormName;

            // parse ignore list
            List<string> ignoreList = IgnoreList
                                            .RemoveLineBreaks()
                                            .Split(",".ToCharArray())
                                            .ToList();

            // get from date
            string fromDate = m_FormFields
                                    .Where(x => x.FieldName == "From")
                                    .SingleOrDefault()
                                    .Value;

            // get to date
            string toDate = m_FormFields
                                    .Where(x => x.FieldName == "To")
                                    .SingleOrDefault()
                                    .Value;

            // parse dates
            DateTime from = fromDate.ToDate(SqlDateTime.MinValue.Value);
            DateTime to = toDate.ToDate(SqlDateTime.MaxValue.Value);

            // get data
            DataTable table = HttpDataService.Instance.FormsyService.GetCSV(FormName, from, to, path, ignoreList);
            //DataView dv = table.DefaultView;

            // convert to csv and send
            FileResponse.OutputCSV(table.AsDataView(), FormName + DateTime.Now);
        }


        #endregion



    }
}
